package cn.zlp.org.service.impl;

import cn.zlp.basic.service.impl.BaseServiceImpl;
import cn.zlp.org.domain.Department;
import cn.zlp.org.mapper.DepartmentMapper;
import cn.zlp.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 部门Service类,先继承公共的Service类,再实现接口
 */
@Service
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class DepartmentServiceImpl  extends BaseServiceImpl<Department> implements IDepartmentService {

    @Autowired(required = false)
    private DepartmentMapper departmentMapper;

    /**
     * 重写新增方法,有特殊业务
     * @param department
     */
    @Override
    @Transactional
    public void add(Department department) {
        departmentMapper.save(department);
        //Department(id=null,  dirPath=null, state=1, parent=Department(id=1), parent_id=null, children=[]) - 选择了上级部门
        //Department(id=null,  dirPath=null, parent=null, parent_id=null, children=[]) - 没有选择上级部门
        if(department.getParent()==null || department.getParent().getId() == null){//你没有选择上级部门
            department.setDirPath("/" + department.getId());
        }else{
            Long id = department.getParent().getId(); //上级部门的id
            Department parentDept = departmentMapper.loadById(id);
            //上级部门的dirPath
            String dirPath = parentDept.getDirPath();
            //设置自己的dirPath
            department.setDirPath(dirPath + "/" + department.getId());
        }
        //修改dirPath
        departmentMapper.update(department);
    }

    /**
     * 重写修改方法,有特殊业务
     * @param department
     */
    @Override
    @Transactional
    public void update(Department department) {
        if(department.getParent()==null || department.getParent().getId() == null){//你没有选择上级部门
            department.setDirPath("/" + department.getId());
        }else{
            Long id = department.getParent().getId(); //上级部门的id
            Department parentDept = departmentMapper.loadById(id);
            //上级部门的dirPath
            String dirPath = parentDept.getDirPath();
            //设置自己的dirPath
            department.setDirPath(dirPath + "/" + department.getId());
        }
        //修改dirPath
        departmentMapper.update(department);
    }

    /**
     * 查询所有部门树,独有方法
     * @return
     */
    @Override
    public List<Department> deptTree() {
        return departmentMapper.deptTree();
    }
}
